<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Brand;
use App\Models\Category;
use App\Models\Good;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class GoodController extends Controller
{
    public function all(Request $request)
    {
        $limit = $request->get('limit', config('pagination.limit'));
        // 关键字搜索
        $title = $request->get('title', '');
        // 分类搜索
        $cat = $request->get('category', 0);

        $query = Good::where('title', 'like', '%' . $title . '%');
        $items = $query
            ->where('category_id', $cat)
            ->paginate($limit);
        return jsonResponse(config('common.successCode'), $items);
    }

    public function create(Request $request)
    {
        $validator = $this->validate($request);
        if ($validator->fails()) {
            return jsonResponse(config('common.validatorError'), $validator);
        }

        $cat = $request->get('category');
        $category = Category::find($cat);
        if (empty($category) && $cat != 0) {
            return jsonResponse(41300);
        }
        $brandId = $request->get('brand');
        $brand = Brand::find($brandId);
        if (empty($brand) && $brandId != 0) {
            return jsonResponse(41301);
        }
        $title = $request->get('title');

        $good = new Good();
        $good['title'] = $title;
        $good['category_id'] = $cat;
        $good['brand_id'] = $brandId;
        $good->save();
        return jsonResponse();
    }

    public function update(Request $request, $id)
    {
        $validator = $this->validate($request);
        if ($validator->fails()) {
            return jsonResponse(config('common.validatorError'), $validator);
        }

        $cat = $request->get('category');
        $category = Category::find($cat);
        if (empty($category) && $cat != 0) {
            return jsonResponse(41300);
        }
        $brandId = $request->get('brand');
        $brand = Brand::find($brandId);
        if (empty($brand) && $brandId != 0) {
            return jsonResponse(41301);
        }
        $title = $request->get('title');

        $good = Good::find($id);
        if (empty($good)) {
            return jsonResponse(40000);
        }
        $good['title'] = $title;
        $good['category_id'] = $cat;
        $good['brand_id'] = $brandId;
        $good->save();
        return jsonResponse();
    }

    public function destroy($id)
    {
        Good::destroy($id);
    }

    private function validate($request)
    {
        return Validator::make($request->all(), [
            'title' => 'required',
            'category' => 'required',
            'brand' => Rule::in([0, 1]),
        ], [
            'title.required' => '名称不能为空',
            'category.required' => '分类不能为空',
            'brand.required' => '品牌不能为空',
        ]);
    }
}
